import { toast, loading } from '@/common';
import { useUser } from '@/store';
// 此vm参数为页面的实例，可以通过它引用vuex中的变量
export const Request = (vm) => {
  // 初始化请求配置
  uni.$uv.http.setConfig((config) => {
    /* config 为默认全局配置*/
    config.baseURL = 'https://touyanbao-api.sinmore.vip';
    config.imageUrl = 'https://touyanbao.oss-cn-beijing.aliyuncs.com'
    config.webUrl = 'http://touyanbao-app-h5.sinmore.vip/#';
    config.header = {
      'Content-Type': 'application/json; charset=utf-8',
    }
    config.responseType = '';
    return config
  })

  // 请求拦截
  uni.$uv.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    const token = uni.getStorageSync('token');
    let urlList = ['api/user/mobilelogin', 'api/user_third/userThirdLogin', 'api/user_third/bindUserMobile', 'api/user_third/bindUserThird', 'api/association_theme/getAssociationThemeDetail', 'api/news/getNewsInfo', 'api/lesson/getLessonDetails', 'api/survey/getSurveyDetail', 'api/association/getAssociationDetail'];
    if(!token && !urlList.includes(config.url)){
      return uni.reLaunch({
        url: '/pages/login/index'
      });
    }
    config.data = config.data || {};
    if (useUser().token) {
    	config.header.token = useUser().token
    	// 二次验证
    	if (!config.header.token) {
        uni.hideLoading();
        uni.navigateTo({
        	url: '/pages/login/index',
        });
    		return;
    	}
    }
    if(!config.custom.loading) loading('加载中...', true);
    return config
  }, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
  })

  // 响应拦截
  uni.$uv.http.interceptors.response.use((res) => {
    uni.hideLoading();
    if(res.statusCode == 200){
      const data = res.data;
      if(data.code == 0 && !res.config.custom.toast){
        return toast(data.msg)
      }else if(data.code == 1){
        return data;
      }
      return data;
    }else{
      toast('错误码：' + res.statusCode)
    }
  }, (err) => {
    console.log(err.data);
    uni.hideLoading();
    if(err.statusCode == 401){
      if(err.config.custom.toast != 0) toast('登录失效，请重新登录');
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
      useUser().setToken('');
      useUser().setUserInfo('');
      setTimeout(() => {
        uni.hideLoading();
        uni.redirectTo({
        	url: '/pages/login/index',
        });
      }, 1000);
    }else{
      console.log('错误码：' + err.statusCode)
    }
  })
}